$(function(){


    if(!Number($('#inventory').html()) > 0){
        $("#buy").attr("disabled",true);
    }

    countdown.setLabels(
            ' 毫秒| 秒| 分| 小时| 天| 周| 月| year| decade| century| millennium',
            ' 毫秒| 秒| 分| 小时| 天| 周| 月| year| decade| century| millennium',
            '',
            null,
            '0');
    end = moment($("#end_time").html(), "YYYY-MM-DD HH:mm:ss");
    start = moment($("#start_time").html(), "YYYY-MM-DD HH:mm:ss");
    now = moment();
    if(start.unix() > now.unix()){
        $("#countdown").html("<strong>待开始</strong>");
        $('#numberspinner').numberspinner({
            disabled: true
        });
        $("#buy").attr("disabled",true);
    }
    else{
        var timer  = setInterval(function(){
            $("#countdown").html("<strong>还剩\t</strong>"+countdown(moment(), end).toHTML("strong"));
            if (moment() >= end){
                clearInterval(timer);
                $("#countdown").html("<strong>已结束</strong>");
                $("#inventory").html("0");
                $('#numberspinner').numberspinner({
                    disabled: true
                });
                $("#buy").attr("disabled",true);
            }
        },
        1000);
    }
    $('#buy').click(function(event) {
            var quantity = $("#numberspinner").numberspinner('getValue');
            var itemid = $("#itemid").html();
            $.post('/holdItem',{'itemid':itemid, 'quantity':quantity, 'openid':$.cookie('openid')}, function(data, status){
                if(data.result){
                    url = 'http://'+window.location.host+'/addr';
                    url += '?id='+itemid;
                    url += '&quantity='+quantity;
                    url += '&task_id='+data.result;
                    window.location.href = url;
                }
                else{
                    sweetAlert("已售罄", "等等看也许有机会", "error");
                }
            });

    });

    function reAuth(){
        swal({ title: "微信授权中...", timer: 2000, showConfirmButton: false });
        setTimeout(function(){
            url = encodeURIComponent('http://'+window.location.host+window.location.pathname+"?id="+$('#itemid').html());
            redirectUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5bf47679c84ef3c8&redirect_uri='+url+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
            window.location.href = redirectUrl;
        }, 2000);
    }

});

